<template>
    <div>
        <div v-if="mode === 'DESIGN'">
            <!--组件在设计器中的样子-->
            <el-select class="max-fill" v-if="!expanding" size="medium" v-model="_value" disabled
                :placeholder="placeholder" />
            <el-radio-group v-model="_value" v-else>

            </el-radio-group>

        </div>
        <div v-else>
            <!--组件在预览及真实显示的样子-->
            <!-- 多选 -->
            <div v-if="multiple">
                <!-- //固定选项 -->
                <div v-if="optionMode === 'fixed'">
                    <el-select :disabled="!editable" :multiple="true" class="max-fill" v-if="!expanding"
                        v-model="_value" size="medium" clearable :placeholder="placeholder">
                        <el-option v-for="(op, index) in options" :key="index" :value="_opValue(op)"
                            :label="_opLabel(op)"></el-option>
                    </el-select>
                </div>
                <!-- 动态加载 -->
                <div v-else>
                    <el-select :disabled="!editable" :multiple="true" class="max-fill" v-if="!expanding"
                        v-model="_value" size="medium" clearable :placeholder="placeholder">
                        <el-option v-for="(op, index) in loadingOptions" :key="index" :value="_opValue(op)"
                            :label="_opLabel(op)"></el-option>
                    </el-select>
                </div>
            </div>
            <!-- 单选 -->
            <div v-else>
                <!-- 固定选项 -->
                <div v-if="optionMode === 'fixed'">
                    <el-select :disabled="!editable" class="max-fill" v-if="!expanding" v-model="_value" size="medium"
                        clearable :placeholder="placeholder">
                        <el-option v-for="(op, index) in options" :key="index" :value="_opValue(op)"
                            :label="_opLabel(op)"></el-option>
                    </el-select>
                    <el-radio-group v-model="_value" v-else>
                        <el-radio v-for="(op, index) in options" :key="index" :value="_opValue(op)"
                            :label="_opLabel(op)">{{
            _opLabel(op) }}</el-radio>
                    </el-radio-group>
                </div>
                <!-- 动态加载 -->
                <div v-else>
                    <el-select :disabled="!editable" class="max-fill" v-if="!expanding" v-model="_value" size="medium"
                        clearable :placeholder="placeholder">
                        <el-option v-for="(op, index) in loadingOptions" :key="index" :value="_opValue(op)"
                            :label="_opLabel(op)"></el-option>
                    </el-select>
                    <el-radio-group v-model="_value" v-else>
                        <el-radio v-for="(op, index) in loadingOptions" :key="index" :value="_opValue(op)"
                            :label="_opLabel(op)">{{
            _opLabel(op) }}</el-radio>
                    </el-radio-group>
                </div>

            </div>
        </div>
    </div>
</template>

<script>
//混入配置
import componentMinxins from '../ComponentMinxins'
import axios from 'axios'
import { sendRequest } from '../../../../api/request'
import { getToken } from '../../../../api/auth'
export default {
    mixins: [componentMinxins],
    name: "AdvancedPicker",
    components: {},
    props: {
        value: {
            type: Array,
            default: () => {
                return []
            }
        },
        placeholder: {
            type: String,
            default: '请选择内容'
        },
        //是否展开
        expanding: {
            type: Boolean,
            default: false
        },
        options: {
            type: Array,
            default: () => {
                return []
            }
        },
        //是否多选
        multiple: {
            type: Boolean,
            default: false
        },
        //选项模式
        optionMode: {
            type: String,
            default: 'fixed'
        },
        loadingData: {
            type: Object,
            default: () => {
                return {}
            }
        }
    },

    computed: {
        _value: {
            get() {
                if (this.multiple) {//多选
                    var arrValue = [];
                    this.value?.forEach(element => {
                        arrValue.push(element.value)
                    });
                    return arrValue;
                }else {//单选
                    return this.value?.[0]?.value
                }
            },
            set(val) {
                if (this.multiple) {//多选
                    var arrValue = [];
                    Array.from(val).forEach(element => {
                        var label = '';
                        if (this.optionMode === 'fixed')//固定模式
                        {
                            label = this.options.find(item => item.value === element).label

                        } else {//动态模式
                            label = this.loadingOptions.find(item => item.value === element).label
                        }
                        arrValue.push({ value: element, label: label })
                    });
                    this.$emit('input', arrValue)
                } else {//单选
                    if (this.optionMode === 'fixed') {//固定模式
                        this.$emit('input', [{ value: val, label: this.options.find(item => item.value === val).label }])
                    } else {//动态模式
                        var label = this.loadingOptions.find(item => item.value === val).label
                        this.$emit('input', [{ value: val, label: label }])
                    }

                }
            }
        }
    },
    data() {
        return {
            loadingOptions: []
        }
    },
    mounted() {

        this.InitLoadOption()
    },
    methods: {
        //当为动态数据时候加载数据
        InitLoadOption() {
            if (this.optionMode === 'fixed') {

            } else {
                var jsonHeaders = {};
                var jsonForms = {};
                this.loadingData.headers?.forEach(element => {
                    jsonHeaders[element.headerName] = element.headerValue
                });
                this.loadingData.body.formData?.forEach(element => {
                    jsonForms[element.key] = element.value
                })
                // 创建一个 axios 实例
                const axiosInstance = axios.create();

                // 请求拦截器(注入方法)
                axiosInstance.interceptors.request.use(config => {
                    // 在请求发起前的处理
                    // console.log('Request config:', config);

                    var ctx = config;
                    let x = eval('(' + this.loadingData.preHandler + ')');//执行的是当前作用域
                    let token = getToken();
                    x(ctx, token);
                    // 你可以在这里修改请求配置，例如添加请求头
                    // config.headers['Authorization'] = 'Bearer your-token';

                    return config;
                }, error => {
                    // 请求错误时的处理
                    // console.error('Request error:', error);
                    return Promise.reject(error);
                });

                // 响应拦截器（注入方法）
                axiosInstance.interceptors.response.use(response => {
                    // 在响应返回后的处理
                    // console.log('Response:', response);
                    let rsp = response;
                    // 在这里处理响应数据
                    let x = eval('(' + this.loadingData.aftHandler + ')');//执行的是当前作用域
                    x(rsp);
                    // eval('console.log(rsp)');//执行的是当前作用域
                    // 你可以在这里处理响应数据
                    // 例如，对数据进行格式化或检查响应状态

                    return response.data; // 只返回数据部分
                }, error => {
                    // 响应错误时的处理
                    console.error('Response error:', error);
                    return Promise.reject(error);
                });
                //发送请求
                sendRequest(
                    axiosInstance,
                    this.loadingData.url,
                    this.loadingData.method,
                    this.loadingData.headers !== null && this.loadingData.headers.length > 0 ? jsonHeaders : null,
                    this.loadingData.body.mode === 'form' ? (this.loadingData.body.formData !== null && this.loadingData.body.formData.length > 0 ?  jsonForms: null) : null,
                    this.loadingData.body.mode === 'json' ? this.loadingData.body.jsonData : null
                ).then(res => {
                    // console.log(res)
                    if (res.code === 200) {
                        this.loadingOptions = res.data
                    }
                })
            }
        }
    },
    watch: {
        options: {
            handler(val) {
                this.loadingOptions = val
            }
        }
    }
}
</script>